package com.lib.common.base.web.bridge

import wendu.dsbridge.CompletionHandler
import java.lang.ref.WeakReference


/**
 * Copyright (C), 2019-2020
 * FileName: NativeBridge
 * Author: Kevin
 * Date: 2020-01-15 10:54
 * Description: js 主动调用 原生的 桥接 方法 辅助类
 * History:
 * <author> <time> <version> <desc>
 * 作者姓名 修改时间 版本号 描述
 */
class JsToNativeBridgeMethodHelper {

    /**
     * 方法 map，key 是方法 js 要调用的方法名
     */
    private val mMethodMap = mutableMapOf<String, (msg: Any, handler: CompletionHandler<String?>) -> Unit>()

    /**
     * CompletionHandler 的map，key 是方法名，value 是改方法的 CompletionHandler 的参数的弱引用
     */
    private val mCompletionHandlerMap = mutableMapOf<String, WeakReference<CompletionHandler<String?>>>()

    /**
     *  增加方法
     */
    fun addMethod(methodName: String,
                  method: (msg: Any, handler: CompletionHandler<String?>) -> Unit) {
        mMethodMap[methodName] = method
    }

    /**
     *  缓存 CompletionHandler
     */
    fun addCompletionHandlerToCache(methodName: String, handler: CompletionHandler<String?>) {
        mCompletionHandlerMap[methodName] = WeakReference(handler)
    }

    /**
     * 从缓存获取 CompletionHandler，并从缓存删除该 CompletionHandler
     */
    fun getCompletionHandlerFromCache(methodName: String): CompletionHandler<String?>? {
        return mCompletionHandlerMap.remove(methodName)?.get()
    }

    /**
     * 调用方法
     */
    fun callMethod(msg: Any, handler: CompletionHandler<String?>) {
        val methodName = getMethodName(msg)
        if (methodName.isNullOrEmpty()) return

        mMethodMap[methodName]?.let {
            it(msg, handler)
        }
    }

    /**
     * 从参数获取 方法名
     */
    fun getMethodName(msg: Any): String? {
        return ""
    }
}